package cn.jbit.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2020/8/9
 */
public class NettyClient{

    private ChannelFuture cFuture;

    public  void  connection(int port,String host) throws Exception{

        EventLoopGroup  group=new NioEventLoopGroup(); //线程组
        try {
            //客户端引导程序
            Bootstrap b=new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });
                    cFuture=b.connect(host,port).sync(); //连接远程节点，阻塞等待直到连接完成
                    cFuture.channel().closeFuture().sync();//阻塞直到Channel关闭
                    cFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                    @Override
                    public void operationComplete(Future<? super Void> future) throws Exception {
                        ByteBuf byteBuf= Unpooled.copiedBuffer("hi netty server", CharsetUtil.UTF_8);
                        cFuture.channel().writeAndFlush(byteBuf);
                    }
            });
        }catch (Exception e){

        }finally {
                group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
            int port=8080;

            NettyClient  client=new NettyClient();
            client.connection(8080,"localhost");
            ChannelFuture channelFuture=client.getcFuture();
    }


    public ChannelFuture getcFuture() {
        return cFuture;
    }

    public void setcFuture(ChannelFuture cFuture) {
        this.cFuture = cFuture;
    }
}
